package com.senlingspace.framework.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.senlingspace.common.utils.StringUtils;
import com.senlingspace.framework.config.properties.WeChatProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序配置
 *
 * @author lebronjames
 * @date 2024/09/26
 */
@Slf4j
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WeChatProperties.class)
public class WeChatConfig {

    private final WeChatProperties weChatProperties;

    @Bean
    public WxMaService wxMaService() {
        log.info("初始化微信小程序配置:");
        if (StringUtils.isBlank(weChatProperties.getMiniAppId()) || StringUtils.isBlank(weChatProperties.getMiniAppSecret())) {
            throw new WxRuntimeException("微信小程序配置信息未配置！");
        }

        WxMaService service = new WxMaServiceImpl();
        Map<String, WxMaConfig> map = new HashMap<>();
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setSecret(weChatProperties.getMiniAppSecret());
        config.setAppid(weChatProperties.getMiniAppId());
        map.put(weChatProperties.getMiniAppId(), config);
        service.setMultiConfigs(map);
        log.info("微信小程序配置初始化完成！");
        return service;
    }

}
